//
//  CHBTabBar.swift
//  weibo.chb
//
//  Created by 褚红彪 on 16/1/20.
//  Copyright © 2016年 chuhongbiao. All rights reserved.
//

import UIKit

class CHBTabBar: UITabBar {
    var composeButtonClosure : (()->())?
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    //重写init方法就必须重写下面这个方法
    required init?(coder aDecoder: NSCoder) {
       fatalError("init(coder:)has not been implemented")
    }
    //在下面的方法里对子控件进行布局
    override func layoutSubviews() {
        super.layoutSubviews()
        let childW = frame.width / 5
        //print(subviews)
        //UITabBarButton
        //如果控件是私有的不能直接获取它的classs
        var index = 0
        for childView in subviews{
            if childView.isKindOfClass(NSClassFromString("UITabBarButton")!)
            {
                let x = CGFloat(index) * childW
                childView.frame = CGRect(x: x, y: 0, width: childW, height: frame.height)
                index++
                if index == 2 {
                    index++
                }
            }
        }
        composeButton.center = CGPointMake(frame.width * 0.5, frame.height * 0.5)
    }
    //设置UI的方法
    func setupUI(){
        addSubview(composeButton)
    }
    @objc private func composeButtonClick(sender : UIButton?){
        composeButtonClosure!()
        print("撰写按钮点击")
    }
    //懒加载撰写按钮
    lazy var composeButton : UIButton = {
        let composeButton = UIButton()
        //给撰写按钮注册一个点击事件
        composeButton.addTarget(self, action: "composeButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
        //设置撰写按钮的背景图片
        composeButton.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        composeButton.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        //设置撰写按钮的图片
        composeButton.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        composeButton.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        //设置按钮的大小，让它自适应图片的大小
        composeButton.sizeToFit()
        return composeButton
    }()
}
